// 1.统计指定目录中文件总大小。要考虑目录中还有子目录的情况。可以同步编码,异步更好。
const fs=require('fs')
const path=require('path');
const { promisify } = require('util');
stat=promisify(fs.stat)
readdir=promisify(fs.readdir)
// 同步
function calcSizeSync(dirPath,cb){
    let fileSize=0
    let error=null
    function calc(dirPath,cb1){
        const statObj=fs.statSync(dirPath)
        if(statObj.isDirectory()){
            try {
                const files=fs.readdirSync(dirPath)
                let dirs=files.map(item=>{
                    return path.join(dirPath,item)
                })
                let index = 0
                function next () {
                if (index == dirs.length) return cb1&&cb1()
                    let current = dirs[index++]
                    calc(current, next)
                }
                next()
            } catch (err) {
                error=err
            }
            
        }else{
            fileSize+=statObj.size
            cb1&&cb1()
        }
    }
    calc(dirPath)
    cb(error,fileSize)
}
// 异步
async function calcSize(dirPath,cb){
    let fileSize=0;
    let error=null
    async function calc(dirPath){
        try {
            const statObj=await stat(dirPath)
            if(statObj.isDirectory()){
                const files=await readdir(dirPath)
                let dirs=files.map(item=>{
                    return path.join(dirPath,item)
                })
                let index = 0
                async function next () {
                    if (index < dirs.length){
                        let current = dirs[index++]
                        await calc(current)
                        await next()
                    }
                }
                return await next()
            }else{
                fileSize+=statObj.size
            }
        } catch (err) {
            error=err
        }
    }
    await calc(dirPath)
    cb(error,fileSize)
}
calcSize('test',(err,size)=>{
    if(err) console.log(err)
    else console.log("异步执行文件大小："+size)
})
calcSizeSync('test',(err,size)=>{
    if(err) console.log(err)
    else console.log("同步执行文件大小："+size)
})